import { Meta } from "@storybook/addon-docs/blocks";
import { useEffect } from 'react';
import { createProviderState } from '../src/hooks/createProviderState';

export const useScreenState = createProviderState((set, get) => ({
  width: 0,
  sizeType: 'desktop',
  isMobile: false,
  
  // 方法定义
  updateSize: () => {
    const width = window.innerWidth;
    const isMobile = width < 768;
    set({ 
      width,
      isMobile,
      sizeType: isMobile ? 'mobile' : 'desktop' 
    });
  },
  
  checkIsMobile: () => get().width < 768
}));

export function ChildComponent() {
  // 选择性获取需要的状态和方法
  const { isMobile, checkIsMobile } = useScreenState();
  
  return (
    <div style={{ 
      border: '1px solid green',
      padding: '1rem',
      marginTop: '1rem',
      background: isMobile ? '#f0f0f0' : 'white'
    }}>
      <h3>子组件</h3>
      <button onClick={() => alert(`Is mobile: ${checkIsMobile()}`)}>
        检查设备类型
      </button>
    </div>
  );
}

export function ParentComponent() {
  // 方式1：获取整个state
  const {width,sizeType} = useScreenState();
  // 方式2：选择性获取（推荐）
  const { updateSize } = useScreenState();

  useEffect(() => {
    updateSize();
    window.addEventListener('resize', updateSize);
    return () => window.removeEventListener('resize', updateSize);
  }, [updateSize]);

  return (
    <div style={{ border: '2px solid blue', padding: '1rem' }}>
      <h2>父组件</h2>
      <p>Width: {width}px | Type: {sizeType}</p>
      <ChildComponent />
    </div>
  );
}





<Meta title="Hooks/ZustandStyleDemo" />

<ParentComponent />